# docstring
__version__ = "$Revision: 66 $"
# $Id: views.py 66 2008-08-31 22:26:38Z AxisOfEntropy $

from django.http import HttpResponse
from django.views.generic.simple import direct_to_template

# Import the Django helpers
import facebook.djangofb as facebook

# The User model defined in models.py
from models import User

# We'll be wrapping the base cv views, but we don't want namespace collisions.
import cv.views

# TODO: get the facebook_canvas_rul context processor to work so that we don't need to fetch it this way.
from django.conf import settings

# We'll require login for our canvas page. This
# isn't necessarily a good idea, as we might want
# to let users see the page without granting our app
# access to their info. See the wiki for details on how
# to do this.

@facebook.require_login()
def learnerInformation_display(request):
    return direct_to_template(request, 'learnerinformation_display.fbml')

@facebook.require_login()
def learnerInformation_render_html(request):
    '''Wrap the cv.views.learnerInformation_html_v12 class, to render and display this Facebook user's information'''
    # Get the User object for the currently logged in user
    user = User.objects.get_current()
    
    return cv.views.learnerInformation_html_v12(request, object_id=user.learner_information_id)

@facebook.require_login()
def learnerInformation_update(request, form='basic', 
        tab_list=[
            'basic',
            'contact',
            'education',
            'work',
            'skills',
            'additional',
            'photo',
        ]):
    '''Wrap the cv.views.learnerInformation_update class, to update this Facebook user's information'''
    # Get the User object for the currently logged in user
    user = User.objects.get_current()
    
    try:
        context = {'facebook_canvas_url': settings.FACEBOOK_CANVAS_URL}
    except:
        context = {'facebook_canvas_url': 'http://apps.facebook.com/cv-creative/'}

    context.update({'body_id': form})
    
    return cv.views.learnerInformation_update(request, tab_list=tab_list, form=form, object_id=user.learner_information_id, template_name="edit.fbml", extra_context=context)

@facebook.require_login()
def learnerInformation_work_update(request, form='work', 
        tab_list=[
            'basic',
            'contact',
            'education',
            'work',
            'skills',
            'additional',
            'photo',
        ]):
    '''Wrap the cv.views.learnerInformation_update class, to update this Facebook user's information'''
    # Get the User object for the currently logged in user
    user = User.objects.get_current()
    
    try:
        context = {'facebook_canvas_url': settings.FACEBOOK_CANVAS_URL}
    except:
        context = {'facebook_canvas_url': 'http://apps.facebook.com/cv-creative/'}

    return cv.views.learnerInformation_work_update(request, object_id=user.learner_information_id, template_name="formset.fbml", extra_context=context, tab_list=tab_list, form=form)

@facebook.require_login()
def learnerInformation_education_update(request, form='education', 
        tab_list=[
            'basic',
            'contact',
            'education',
            'work',
            'skills',
            'additional',
            'photo',
        ]):
    '''Wrap the cv.views.learnerInformation_update class, to update this Facebook user's information'''
    # Get the User object for the currently logged in user
    user = User.objects.get_current()
    
    try:
        context = {'facebook_canvas_url': settings.FACEBOOK_CANVAS_URL}
    except:
        context = {'facebook_canvas_url': 'http://apps.facebook.com/cv-creative/'}

    return cv.views.learnerInformation_education_update(request, object_id=user.learner_information_id, template_name="formset.fbml", extra_context=context, tab_list=tab_list, form=form)

@facebook.require_login()
def learnerInformation_photo_update(request, form='photo', 
        tab_list=[
            'basic',
            'contact',
            'education',
            'work',
            'skills',
            'additional',
            'photo',
        ]):
    """Wrap the cv.views.learnerInformation_photo_update class, to update this Facebook user's information
    
    Note that the form this renders and accepts goes directly to this application's server, not through Facebook."""
    # Get the User object for the currently logged in user
    user = User.objects.get_current()
    
    try:
        context = {'facebook_canvas_url': settings.FACEBOOK_CANVAS_URL}
    except:
        context = {'facebook_canvas_url': 'http://apps.facebook.com/cv-creative/'}

    return cv.views.learnerInformation_photo_update(
        request,
        object_id=user.learner_information_id,
        template_name="photo_form.fbml",
        extra_context=context,
        tab_list=tab_list, form=form,
        post_save_redirect=settings.FACEBOOK_CANVAS_URL + 'update/photo/',
    )

@facebook.require_login()
def learnerInformation_download(request):
    '''Return a response showing options for exporting/downloading the CV in other formats.'''
    # Get the User object for the currently logged in user
    user = User.objects.get_current()

    # This section takes some explaining.
    # All of these facebook views expect to be passed fb_ parameters in the HTTP request, either GET or POST.
    # If a facebook user wants to request a file from this server directly (not facebook requesting on their behalf) then the end user's browser will need to include these fb_ parameters.
    # Perhaps the easiest way to accomplish this is to include the fb_ parameters as GET variables in the link we provide.
    # (This is similar to the way Facebook embeds iframes with the <fb:iframe> FBML tag.)
    # To do this, when we render the facebook canvas page which shows all the download links, we take the variables from that POST request and rewrite them into a string of GET variables, suitable for tacking on the end of a URL in a link.
    # This lets the end user's browser emulate Facebook's servers.
    # TODO: If we included all variables, the GET string would be vary long indeed.  So we should only include the necessary ones.
    
    # This didn't quite work:
    # variables = {
        # 'fb_sig_in_iframe': '1',
        # 'fb_sig_time': request.POST['fb_sig_time'], 
        # 'fb_sig_added': request.POST['fb_sig_added'], 
        # 'fb_sig_user': request.POST['fb_sig_user'], 
        # 'fb_sig_profile_update_time': request.POST['fb_sig_profile_update_time'], 
        # 'fb_sig_session_key': request.POST['fb_sig_session_key'], 
        # 'fb_sig_expires': request.POST['fb_sig_expires'], 
        # 'fb_sig_api_key': request.POST['fb_sig_api_key'], 
        # 'fb_sig': request.POST['fb_sig'], 
    # }
    
    pairs = []
    for key in request.POST.keys():
        pairs.append(key + '=' + request.POST[key])
    get_string = '?' + '&'.join(pairs)
    
    return direct_to_template(request, 'export.fbml', extra_context={'fbuser': user, 'get_string': get_string})

@facebook.require_login()
def learnerInformation_export(request, format, content_type):
    '''Wrap the cv getDocumentFromEuropass view, specifying the filename'''
    # Get the User object for the currently logged in user
    user = User.objects.get_current()
    
    l = user.learner_information
    object_id = l.id
    file_base_name = l.firstname + '_' + l.lastname
    
    return cv.views.getDocumentFromEuropass(
        request, 
        id=object_id, 
        format=format, 
        content_type=content_type, 
        file_base_name=file_base_name, 
    )

@facebook.require_login()
def learnerInformation_export_american(request, format, content_type):
    '''Wrap the cv getDocumentFromEuropass view, specifying the filename'''
    # Get the User object for the currently logged in user
    user = User.objects.get_current()

    l = user.learner_information
    object_id = l.id
    file_base_name = l.firstname + '_' + l.lastname

    return cv.views.learnerInformation_american_convert(
        request, 
        object_id=object_id, 
        format=format, 
        mimetype=content_type, 
        file_base_name=file_base_name, 
    )

@facebook.require_login()
def invite(request):
    '''Return a response page with widgets to allow users to invite their friends to use this application.'''
    # Get the User object for the currently logged in user
    user = User.objects.get_current()

    #HTML escape function for invitation content.
    from cgi import escape

    # Much of this is copied from http://wiki.developers.facebook.com/index.php/Fb:request-form#Examples
    # Gah I had to actually fix the example in their wiki: http://wiki.developers.facebook.com/index.php?title=Fb:request-form&diff=prev&oldid=14228
    fql = "SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1='%s') AND has_added_app = 1" % user.id
    result = request.facebook.fql.query(fql) 
    
    # Extract the user ID's returned in the FQL request into a new array. 
    if result and isinstance(result, list):
        friends_list = map(lambda x: str(x['uid']), result)
    else:
        friends_list = []
    # Convert the array of friends into a comma-delimeted string.
    exclude_ids = ','.join(friends_list) 
    
    # Prepare the invitation text that all invited users will receive.
    invitation_content = '''<fb:name uid="%s" firstnameonly="true" shownetwork="false"/> has invited you to create your resume or CV online with <fb:application-name />!
    <fb:req-choice url="%s" label="Get started with CV-Creative" />
    ''' % (user.id, request.facebook.get_add_url())
    
    invitation_content = escape(invitation_content, True)
    
    return direct_to_template(request, 'invite.fbml', extra_context={
        'fbuser': user, 
        'invitation_content': invitation_content, 
        'exclude_ids': exclude_ids, 
    })